'strict'
const Joi = require("joi");
const pmModel = require('../models/pmModel');
const pm_validate = require("../validates/pm_validate");
const logger = require('../logger');
const pmUtils = require("../utils/pmUtils");


/**
 * 项目管理控制器模块类
 */

class pmController {

    /**
     * 查询项目列表控制器
     * @param {*} ctx 
     * @param {*} next 
     */
    static async getPmList(ctx, next) {
        const params = ctx.query;
        logger.info("查询项目列表请求参数：", params);

        // 校验请求参数
        const {
            error
        } = Joi.validate(params, pm_validate.getPmList, {
            allowUnknown: true
        });
        let err_msg = "";
        if (error != null) {
            err_msg = error.details[0] ? error.details[0].message : "字段格式非法！";
            ctx.body = pmUtils.responseBody("02", err_msg);
            return;
        }
        if (!params.size) {
            params.size = 10;
        }

        // 处理条件不同的sql
        let status_sql = "";
        if (params.p_status == "0") {
            status_sql = "WHERE p_status != 3";
        } else if (params.p_status == "1") {
            status_sql = "WHERE p_status = 3";
        }

        try {
            // 查询当前条件下有无数据
            const totalObj = await pmModel.countPmlist({
                status_sql: status_sql
            });
            const totalPage = Math.ceil(totalObj[0].total / params.size);
            if (totalObj[0].total <= 0) {
                ctx.body = { ...pmUtils.responseBody("01", "当前条件下数据为空"),
                    totalPage: totalPage,
                    p_list: []
                };
                return;
            }

            // 当前条件下有数据
            let start = (params.page - 1) * params.size;
            let keys = 'id, p_name, p_rank, p_status, p_news, p_manager, p_online_time, p_fuplus_status';
            const p_list = await pmModel.getPmList({
                keys: keys,
                start: start,
                size: params.size,
                status_sql: status_sql
            });
            ctx.body = { ...pmUtils.responseBody("01", "查询成功"),
                totalPage: totalPage,
                p_list: p_list
            };
        } catch (err) {
            ctx.throw(500, err.message);
            return;
        }
    }

    /**
     * 查询项目详情控制器
     * @param {*} ctx 
     * @param {*} next 
     */
    static async getPmDetail(ctx, next) {
        const params = ctx.params;
        logger.info("查询详情请求参数：", params);

        // 校验参数
        let err_msg = "";
        const {
            error
        } = Joi.number().integer().positive().validate(params.id);
        if (error != null) {
            err_msg = error.details[0] ? error.details[0].message : "字段格式非法！";
            ctx.body = pmUtils.responseBody("02", err_msg);
            return;
        }

        try {
            const result = await pmModel.getPmDetail(params.id);
            ctx.body = { ...pmUtils.responseBody("01", "查询成功"),
                ...result[0]
            };
        } catch (err) {
            ctx.throw(500, err.message);
            return;
        }
    }

    /**
     * adPmData 添加项目控制器
     * @param {*} ctx  上下文对象
     * @param {*} next 
     */
    static async adPmData(ctx, next) {
        const params = ctx.request.body;
        logger.info('添加项目请求参数：', params);

        // 校验必传参数, 限制传未定义参数
        const {
            error
        } = Joi.validate(params, pm_validate.adPmData, {
            allowUnknown: false
        });
        let err_msg = "";
        if (error != null) {
            err_msg = error.details[0] ? error.details[0].message : "字段格式非法！";
            ctx.body = pmUtils.responseBody("02", err_msg);
            return;
        }

        try {
            let keys = [];
            let values = [];
            for (let key in params) {
                if (params[key] === '') {
                    continue;
                }
                keys.push(key);
                values.push(`'${params[key]}'`);
            }

            await pmModel.adPmData({
                keys,
                values
            });
            ctx.body = pmUtils.responseBody("01", "添加项目成功");
        } catch (err) {
            ctx.throw(500, err.message);
            return;
        }
    }

    /**
     * 更新项目状态
     * @param {*} ctx 
     * @param {*} next 
     */
    static async updatePmData(ctx, next) {
        const params = ctx.request.body;
        logger.info("更新项目请求参数：", params);

        // 校验参数，不允许传未定义参数
        const {
            error
        } = Joi.validate(params, pm_validate.updatePmData, {
            allowUnknown: false
        });
        let err_msg = "";
        if (error != null) {
            err_msg = error.details[0] ? error.details[0].message : "字段格式非法！";
            ctx.body = pmUtils.responseBody("02", err_msg);
            return;
        }

        try {
            // 拼接sql语句
            let updateSql = "set ";
            for (let key in params) {
                if (params[key] === '' || key === 'id') {
                    continue;
                }
                updateSql += (key + "='" + params[key] + "', ");
            }
            updateSql = updateSql.substring(0, updateSql.length - 2);
            await pmModel.updatePmData({
                id: params.id,
                updateSql: updateSql
            });
            ctx.body = pmUtils.responseBody("01", "更新项目成功");
        } catch (err) {
            ctx.throw(500, err.message);
            return;
        }
    }

}

module.exports = pmController;